<template>
  <view class="user-edit">
    <view v-if="loading" class="loading-container">
      <AppLoading text="正在加载用户信息..." />
    </view>

    <view v-else-if="!userInfo" class="error-container">
      <view class="error-content">
        <text class="error-text">用户不存在或已被删除</text>
        <button class="back-btn" @click="handleBack">返回用户列表</button>
      </view>
    </view>

    <view v-else class="edit-container">
      <AppLayout title="编辑用户">
        <view class="form-container">
          <!-- 用户名（只读） -->
          <view class="form-group">
            <FormInput
              label="用户名"
              v-model="formData.username"
              placeholder="用户名"
              :disabled="true"
              note="用户名不可修改"
            />
          </view>

          <!-- 真实姓名 -->
          <view class="form-group">
            <FormInput
              label="真实姓名"
              v-model="formData.realName"
              placeholder="请输入真实姓名"
              :required="true"
              :error="errors.realName"
              @blur="validateRealName"
            />
          </view>

          <!-- 手机号 -->
          <view class="form-group">
            <FormInput
              label="手机号"
              v-model="formData.phone"
              placeholder="请输入手机号"
              type="number"
              :error="errors.phone"
              @blur="validatePhone"
            />
          </view>

          <!-- 邮箱 -->
          <view class="form-group">
            <FormInput
              label="邮箱"
              v-model="formData.email"
              placeholder="请输入邮箱地址"
              type="email"
              :error="errors.email"
              @blur="validateEmail"
            />
          </view>

          <!-- 角色 -->
          <view class="form-group">
            <view class="form-label">
              <text class="label-text">角色</text>
              <text class="required">*</text>
            </view>
            <picker
              :value="roleIndex"
              :range="roleOptions"
              range-key="label"
              @change="handleRoleChange"
            >
              <view class="picker-input" :class="{ error: errors.role }">
                <text>{{ roleOptions[roleIndex].label }}</text>
                <text class="picker-arrow">▼</text>
              </view>
            </picker>
            <text v-if="errors.role" class="error-text">{{ errors.role }}</text>
          </view>

          <!-- 学校（如果角色需要） -->
          <view v-if="needSchool" class="form-group">
            <view class="form-label">
              <text class="label-text">所属学校</text>
              <text class="required">*</text>
            </view>
            <picker
              :value="schoolIndex"
              :range="schoolOptions"
              range-key="label"
              @change="handleSchoolChange"
            >
              <view class="picker-input" :class="{ error: errors.schoolId }">
                <text>{{ schoolOptions[schoolIndex].label }}</text>
                <text class="picker-arrow">▼</text>
              </view>
            </picker>
            <text v-if="errors.schoolId" class="error-text">{{ errors.schoolId }}</text>
          </view>

          <!-- 头像上传 -->
          <view class="form-group">
            <view class="form-label">
              <text class="label-text">头像</text>
            </view>
            <ImageUpload
              v-model="formData.avatar"
              :max-count="1"
              :show-upload-btn="true"
              @change="handleAvatarChange"
            />
          </view>

          <!-- 用户状态 -->
          <view class="form-group">
            <view class="form-label">
              <text class="label-text">用户状态</text>
            </view>
            <picker
              :value="statusIndex"
              :range="statusOptions"
              range-key="label"
              @change="handleStatusChange"
            >
              <view class="picker-input">
                <text>{{ statusOptions[statusIndex].label }}</text>
                <text class="picker-arrow">▼</text>
              </view>
            </picker>
          </view>

          <!-- 备注信息 -->
          <view class="form-group">
            <view class="form-label">
              <text class="label-text">备注信息</text>
            </view>
            <textarea
              v-model="formData.remark"
              class="form-textarea"
              placeholder="请输入备注信息（选填）"
              maxlength="200"
              rows="4"
            />
            <text class="text-count">{{ (formData.remark || '').length }}/200</text>
          </view>
        </view>

        <!-- 操作按钮 -->
        <view class="action-section">
          <button
            class="action-btn cancel-btn"
            @click="handleCancel"
          >
            取消
          </button>
          <button
            class="action-btn save-btn"
            :loading="saving"
            @click="handleSave"
          >
            {{ saving ? '保存中...' : '保存' }}
          </button>
        </view>
      </AppLayout>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { userAPI, type User, type UserUpdateRequest } from '@/api/user'
import AppLoading from '@/components/common/AppLoading.vue'
import AppLayout from '@/components/common/AppLayout.vue'
import FormInput from '@/components/common/FormInput.vue'
import ImageUpload from '@/components/common/ImageUpload.vue'

// 响应式数据
const loading = ref(true)
const saving = ref(false)
const userInfo = ref<User | null>(null)
const userId = ref<string>('')

// 表单数据
const formData = reactive<Partial<UserUpdateRequest> & { remark?: string }>({
  realName: '',
  phone: '',
  email: '',
  role: '',
  schoolId: '',
  avatar: '',
  remark: ''
})

// 表单验证错误
const errors = reactive<Record<string, string>>({})

// 角色选项
const roleOptions = [
  { label: '超级管理员', value: 'ADMIN' },
  { label: '学校管理员', value: 'SCHOOL_ADMIN' },
  { label: '教师', value: 'TEACHER' },
  { label: '家长', value: 'PARENT' }
]

const roleIndex = ref(0)

// 状态选项
const statusOptions = [
  { label: '正常', value: 'ACTIVE' },
  { label: '禁用', value: 'INACTIVE' },
  { label: '锁定', value: 'LOCKED' }
]

const statusIndex = ref(0)

// 学校选项（Mock数据）
const schoolOptions = [
  { label: '请选择学校', value: '' },
  { label: '第一小学', value: 'school1' },
  { label: '第二小学', value: 'school2' },
  { label: '第三小学', value: 'school3' },
  { label: '实验中学', value: 'school4' },
  { label: '育才中学', value: 'school5' }
]

const schoolIndex = ref(0)

// 计算属性
const needSchool = computed(() => {
  return ['SCHOOL_ADMIN', 'TEACHER', 'PARENT'].includes(formData.role || '')
})

// 方法
/**
 * 获取用户信息
 */
const fetchUserInfo = async () => {
  if (!userId.value) {
    loading.value = false
    return
  }

  try {
    loading.value = true
    const response = await userAPI.getUserById(userId.value)
    if (response.code === 200 && response.data) {
      userInfo.value = response.data

      // 填充表单数据
      formData.realName = userInfo.value.realName
      formData.phone = userInfo.value.phone || ''
      formData.email = userInfo.value.email || ''
      formData.role = userInfo.value.role
      formData.schoolId = userInfo.value.schoolId || ''
      formData.avatar = userInfo.value.avatar || ''

      // 设置角色索引
      roleIndex.value = roleOptions.findIndex(item => item.value === userInfo.value!.role)

      // 设置状态索引
      statusIndex.value = statusOptions.findIndex(item => item.value === userInfo.value!.status)

      // 设置学校索引
      if (formData.schoolId) {
        schoolIndex.value = schoolOptions.findIndex(item => item.value === formData.schoolId)
      } else {
        schoolIndex.value = 0
      }
    } else {
      userInfo.value = null
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    userInfo.value = null
    uni.showToast({
      title: '获取用户信息失败',
      icon: 'error'
    })
  } finally {
    loading.value = false
  }
}

/**
 * 验证真实姓名
 */
const validateRealName = () => {
  if (!formData.realName?.trim()) {
    errors.realName = '请输入真实姓名'
  } else if (formData.realName.trim().length < 2) {
    errors.realName = '姓名至少需要2个字符'
  } else if (formData.realName.trim().length > 20) {
    errors.realName = '姓名不能超过20个字符'
  } else {
    delete errors.realName
  }
}

/**
 * 验证手机号
 */
const validatePhone = () => {
  if (formData.phone && !/^1[3-9]\d{9}$/.test(formData.phone)) {
    errors.phone = '请输入正确的手机号'
  } else {
    delete errors.phone
  }
}

/**
 * 验证邮箱
 */
const validateEmail = () => {
  if (formData.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
    errors.email = '请输入正确的邮箱地址'
  } else {
    delete errors.email
  }
}

/**
 * 验证表单
 */
const validateForm = (): boolean => {
  // 清空错误
  Object.keys(errors).forEach(key => delete errors[key])

  // 验证必填字段
  if (!formData.realName?.trim()) {
    errors.realName = '请输入真实姓名'
  }

  if (!formData.role) {
    errors.role = '请选择用户角色'
  }

  if (needSchool.value && !formData.schoolId) {
    errors.schoolId = '请选择所属学校'
  }

  // 验证格式
  validateRealName()
  validatePhone()
  validateEmail()

  return Object.keys(errors).length === 0
}

/**
 * 处理角色变更
 */
const handleRoleChange = (e: any) => {
  roleIndex.value = e.detail.value
  formData.role = roleOptions[roleIndex.value].value

  // 如果角色不需要学校，清空学校选择
  if (!needSchool.value) {
    formData.schoolId = ''
    schoolIndex.value = 0
  }
}

/**
 * 处理学校变更
 */
const handleSchoolChange = (e: any) => {
  schoolIndex.value = e.detail.value
  formData.schoolId = schoolOptions[schoolIndex.value].value
}

/**
 * 处理状态变更
 */
const handleStatusChange = (e: any) => {
  statusIndex.value = e.detail.value
}

/**
 * 处理头像变更
 */
const handleAvatarChange = (avatarUrl: string) => {
  formData.avatar = avatarUrl
}

/**
 * 处理取消
 */
const handleCancel = () => {
  uni.showModal({
    title: '确认取消',
    content: '确定要取消编辑吗？未保存的修改将会丢失。',
    success: (res) => {
      if (res.confirm) {
        uni.navigateBack()
      }
    }
  })
}

/**
 * 处理保存
 */
const handleSave = async () => {
  if (!validateForm()) {
    uni.showToast({
      title: '请检查表单填写',
      icon: 'none'
    })
    return
  }

  if (!userInfo.value) return

  try {
    saving.value = true

    const updateData: UserUpdateRequest = {
      realName: formData.realName,
      phone: formData.phone,
      email: formData.email,
      role: formData.role,
      schoolId: formData.schoolId || undefined,
      avatar: formData.avatar
    }

    const response = await userAPI.updateUser(userInfo.value.id, updateData)

    if (response.code === 200) {
      uni.showToast({
        title: '保存成功',
        icon: 'success'
      })

      // 如果状态有变更，需要单独调用状态更新接口
      const currentStatus = statusOptions[statusIndex.value].value
      if (currentStatus !== userInfo.value.status) {
        try {
          if (currentStatus === 'ACTIVE') {
            await userAPI.activateUser(userInfo.value.id)
          } else {
            await userAPI.deactivateUser(userInfo.value.id)
          }
        } catch (statusError) {
          console.error('更新用户状态失败:', statusError)
          uni.showToast({
            title: '用户状态更新失败',
            icon: 'error'
          })
        }
      }

      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
  } catch (error) {
    console.error('保存用户信息失败:', error)
    uni.showToast({
      title: '保存失败，请重试',
      icon: 'error'
    })
  } finally {
    saving.value = false
  }
}

/**
 * 处理返回
 */
const handleBack = () => {
  uni.navigateBack()
}

// 生命周期
onMounted(() => {
  // 获取页面参数
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  // @ts-ignore
  const options = currentPage.options || {}

  userId.value = options.id || ''

  fetchUserInfo()
})
</script>

<style lang="scss" scoped>
.user-edit {
  min-height: 100vh;
  background: #f5f7fa;
}

.loading-container,
.error-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 60vh;
}

.error-content {
  text-align: center;

  .error-text {
    font-size: 16px;
    color: #666;
    margin-bottom: 20px;
    display: block;
  }

  .back-btn {
    padding: 10px 20px;
    background: #1890ff;
    color: #ffffff;
    border: none;
    border-radius: 6px;
    font-size: 14px;
  }
}

.edit-container {
  padding-bottom: 100px;
}

.form-container {
  background: #ffffff;
  margin: 12px;
  border-radius: 8px;
  padding: 20px;
}

.form-group {
  margin-bottom: 24px;

  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  display: flex;
  align-items: center;
  margin-bottom: 8px;

  .label-text {
    font-size: 14px;
    color: #333;
    font-weight: 500;
  }

  .required {
    color: #f5222d;
    margin-left: 2px;
  }
}

.picker-input {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: #ffffff;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 14px;
  color: #333;

  &.error {
    border-color: #f5222d;
  }

  .picker-arrow {
    font-size: 12px;
    color: #999;
  }
}

.form-textarea {
  width: 100%;
  padding: 12px 16px;
  background: #ffffff;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 14px;
  color: #333;
  line-height: 1.5;
  resize: none;
}

.text-count {
  font-size: 12px;
  color: #999;
  text-align: right;
  display: block;
  margin-top: 4px;
}

.error-text {
  font-size: 12px;
  color: #f5222d;
  margin-top: 4px;
  display: block;
}

.action-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #ffffff;
  padding: 16px 20px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  gap: 12px;

  .action-btn {
    flex: 1;
    padding: 12px 24px;
    border: none;
    border-radius: 6px;
    font-size: 14px;
    font-weight: 500;

    &.cancel-btn {
      background: #f5f5f5;
      color: #666;
    }

    &.save-btn {
      background: #1890ff;
      color: #ffffff;

      &:active {
        opacity: 0.8;
      }
    }
  }
}

// 响应式设计
@media (max-width: 480px) {
  .form-container {
    margin: 8px;
    padding: 16px;
  }

  .action-section {
    padding: 12px 16px;

    .action-btn {
      padding: 10px 20px;
      font-size: 13px;
    }
  }
}
</style>